/**
 * 浮动工具条
 * @author Ly
 * @version 1.0
 */
/**
 * Ly.FloatToolsBar构造函数，此插件依赖于Ly.RoundRect插件。
 * @param {Object} config 配置信息
 * config = {
	 width : 400,
	 height : 300,
	 title : '',
	 html : '',
	 alpha : .3,
	 fun : function() {}
 }
 */
Ly.FloatToolsBar = function(config /* Object */) {
	var _this = this;
	
	config = config || {};
	
	this.handler = {
		win          : null,
		roundRect    : null,
		events       : {},
		customEvents : config.fun || function() {}                         // 此插件触发时所要执行的事件，即当选中文字时
	};
	this.config = {
		id                   : Ly.getCount(),                              // 插件的唯一标识
		width                : config.width || 400,                        // 插件的宽度
		height               : config.height || 300,                       // 插件的高度
		title                : config.title || '',                         // 插件的标题
		content              : config.html || '',                          // 插件的内容
		alpha                : config.alpha || .5,                         // 鼠标未移到插件上时显示的透明度
		minDist              : config.minDist || 300,                      // 鼠标移动时关闭插件的最小距离
		titleBackgroundColor : config.BackGroundColor || '#D4E6FC',        // 标题背景色
		borderColor          : config.borderColor || '#96C2F1',            // 边框颜色
		backgroundColor      : config.backgroundColor || '#EFF7FF',        // 背景色，除标题之外
		selectedContent      : '',                                         // 选中的内容
		selectedXY           : {},                                         // 选取文字时的坐标
		opended              : false                                       // 窗口是否已经被打开
	};
	this.private = {
		// 创建插件主体
		createFrame : function() {
			var config  = _this.config,
				handler = _this.handler;
			
			handler.win = Ly.createElement('div', {
				id    : 'ly-floattoolsbar-win-' + config.id,
				cls   : 'ly-floattoolsbar-win',
				style : 'filter:alpha(opacity=' + config.alpha * 100 + ');opacity:' + config.alpha
			});
			
			handler.roundRect = new Ly.RoundRect({
				container            : handler.win,
				width                : config.width,
				height               : config.height,
				title                : config.title,
				html                 : config.content,
				titleBackgroundColor : config.titleBackgroundColor,
				borderColor          : config.borderColor,
				backgroundColor      : config.backgroundColor
			}).render();
			
			document.body.appendChild(handler.win);
			
			return this;
		},
		// 给插件绑定事件
		bindEvents : function() {
			var config  = _this.config,
				handler = _this.handler,
				events  = handler.events;
			
			// 文档的鼠标弹起事件
			events.bodyMouseUp = function(obj /* Object */, evt /* Object */) {
				var selectionNode = (window.getSelection ? window.getSelection().anchorNode : document.selection.createRange());
				
				config.selectedContent = (window.getSelection ? window.getSelection().toString() : document.selection.createRange().text);
				
				if (config.selectedContent.length > 0) {
					var scrollTop  = document.documentElement.scrollTop || document.body.scrollTop,
						scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft,
						x          = evt.pageX || evt.clientX + scrollLeft - document.body.clientLeft,
						y          = (evt.pageY || evt.clientY + scrollTop - document.body.clientTop) + 20,
						width      = document.body.clientWidth + scrollLeft - document.body.clientLeft,
						height     = document.body.clientHeight + scrollTop - document.body.clientTop;
					
					if (x + config.width > width) {
						 x = x - config.width - 10;
					}
					if (y + config.height > height) {
						y = y - config.height - 30;
					}
					
					if (x < 5) { x = 5; }
					if (y < 5) { y = 5; }
					
					handler.win.style.left = x + 'px';
					handler.win.style.top  = y + 'px';
					
					_this.private.showWin();
					_this.config.opened = true;
					
					// 当为IE时，给范围创建一个parentNode属性
					selectionNode.parentNode || (selectionNode.parentNode = selectionNode.parentElement());
					handler.customEvents.call(_this, evt, selectionNode);
					
					config.selectedXY = {
						x : evt.pageX || evt.clientX,
						y : evt.pageY || evt.clientY
					};
				}
			};
			
			// 插件的鼠标经过事件
			events.winMouseOver = function() {
				this.style.opacity = 1;
				this.style.filter  = 'alpha(opacity=100)';
			};
			
			// 插件的鼠标滑开的事件，要对mouseout事件进行修复。
			events.winMouseOut = function(obj /* Object */, evt /* Object */) {
				var target, contains;
				
				evt    = window.event || evt;
				target = evt.target || evt.srcElement;
				
				if (evt.stopPropagation) {
					evt.stopPropagation();
				} else {
					evt.cancelBubble = true;
				}
				
				if (this.contains && (this.contains(evt.toElement) || this === evt.toElement)) {
					return;
				} else if (Ly.owner(this, target)) {
					return;
				}
				this.style.opacity = config.alpha;
				this.style.filter  = 'alpha(opacity=' + config.alpha * 100 + ')';
			};
			
			// 给插件注册鼠标弹起事件，用来取消在插件中选取文字的事件冒泡
			events.winCancelBubbles = function(obj /* Object */, evt /* Object */) {
				var target;
				
				evt = window.event || evt;
				
				if (evt.stopPropagation) {
					evt.stopPropagation();
				} else {
					evt.cancelBubble = true;
				}
			};
			
			// 文档的单击事件，用来隐藏插件
			events.bodyClick = function(obj /* Object */, evt /* Object */) {
				var target;
				
				evt = evt || window.event;
				
				if ((evt.target || evt.srcElement) !== _this.handler.win && config.selectedContent == '') {
					_this.private.hideWin();
					_this.config.opened = false;
				}
			};
			
			// 文档的鼠标移动事件。用来设置隐藏插件
			events.bodyMouseMove = function(obj /* Object */, evt /* Object */) {
				var dx = (evt.pageX || evt.clientX) - config.selectedXY.x,
					dy = (evt.pageY || evt.clientY) - config.selectedXY.y;
				
				if (Math.sqrt(dx * dx + dy * dy) > config.minDist) {
					_this.private.hideWin();
				} else {
					config.opened && _this.private.showWin();
				}
			};
			
			Ly.addEvent('onmouseup', events.bodyMouseUp, document);
			Ly.addEvent('onmouseover', events.winMouseOver, handler.win);
			Ly.addEvent('onmouseout', events.winMouseOut, handler.win);
			Ly.addEvent('onmouseup', events.winCancelBubbles, handler.win);
			Ly.addEvent('onmousemove', events.winCancelBubbles, handler.win);
			Ly.addEvent('onclick', events.bodyClick, document);
			Ly.addEvent('onmousemove', events.bodyMouseMove, document);
			
			return this;
		},
		// 显示插件
		showWin : function() {
			var config  = _this.config,
				handler = _this.handler;
			
			handler.win.style.display = 'block';
			return this;
		},
		// 隐藏插件
		hideWin : function() {
			var config  = _this.config,
				handler = _this.handler;
			
			handler.win.style.display = 'none';
			return this;
		}
	};
};

Ly.FloatToolsBar.prototype = {
	version : '1.0',
	// 渲染插件
	render : function() {
		this.private.createFrame().bindEvents();
		return this;
	},
	// 隐藏插件
	hide : function() {
		this.private.hideWin();
		this.config.opened = false;
		return this;
	},
	// 显示插件
	show : function() {
		this.private.showWin();
		this.config.opened = true;
		return this;
	},
	// 删除插件
	remove : function() {
		var config  = this.config,
			handler = this.handler,
			events  = handler.events;
		
		Ly.removeEvent(document, 'onmouseup', events.bodyMouseUp);
		Ly.removeEvent(document, 'onclick', events.bodyClick);
		Ly.removeEvent(handler.win, 'onmouseover', events.winMouseOver);
		Ly.removeEvent(handler.win, 'onmouseout', events.winMouseOut);
		Ly.removeEvent(handler.win, 'onmouseup', events.winCancelBubbles);
		Ly.removeEvent(handler.win, 'onmousemove', events.winCancelBubbles);
		Ly.removeEvent(document, 'onmousemove', events.bodyMouseMove);
		
		handler.win.innerHTML = '';
		
		document.body.removeChild(handler.win);
		
		handler.win = null;
	},
	// 获取选取的文字
	getSelectedText : function() {
		return this.config.selectedContent;
	}
};